<?php

namespace App\Http\Controllers\Order;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Fee\FeeTypeController;
use App\Models\Custom\Custom;
use App\Models\Manger\Manger;
use App\Models\Order\Saleorder as ModelSaleorder;
use App\Models\Order\Saleorderfee as ModelSaleorderfee;
use App\Models\Order\SaleorderOtherfeePay;
use App\Models\Order\SaleorderOtherfeePayApprove;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SaleorderOtherfeePayController extends BaseController
{
    /****
     *  销售其他费用，每次付款新增 付款数据，不存在修改，数据撤审后 当前付款数据 废弃
     *
     *
     */
    public function dopostadd(Request $request)
    {
        $otherfee_id = intval($request->otherfee_id);
        $cpid = $this->mangerinfo['cpid'] ?? 0;
        $otherfeeinfo = ModelSaleorderfee::where(['cpid' => $cpid, 'id' => $otherfee_id])->first();

        if (!$otherfeeinfo) {
            return response()->json(['code' => '001', 'msg' => '费用信息不存在']);
        }
        //只允许发起一次付款 查询最新的审批状态  如果不是待审核状态，则不允许发起付款
        $SaleorderOtherfeePay = SaleorderOtherfeePayApprove::where(['cpid' => $cpid, 'otherfee_id' => $otherfee_id])->orderBy('id', 'desc')->first();
        if ($SaleorderOtherfeePay) {
            if ($SaleorderOtherfeePay->status < 4) {
                return response()->json(['code' => '001', 'msg' => '请勿重复发起付款']);
            }
        }
        $company_id = intval($request->company_id);

        //发起付款审核 新增/编辑
        //if($otherfeeinfo->status == '1'){
        DB::beginTransaction();
        try {
            $data = ['is_pay' => 2, 'pay_at' => time(), 'pay_mid' => $this->mangerinfo['id']];
            //$data['total_pieces'] = intval($request->total_pieces);
            $data['custom_name'] = strval($request->custom_name);
            $data['company_id'] = $company_id;
            $company_name = $request->company_name ?? '';
            $data['company_name'] = $company_name;
            $parts = explode('*', $company_name);
            $data['settlement_company'] = isset($parts[1]) ? $parts[1] : '';
            //结算公司根据company_id从公司表获取
            $data['account_name'] = strval($request->account_name);
            $data['bank_card_no'] = strval($request->bank_card_no);
            $data['bank'] = strval($request->bank);
            $data['bank_number'] = strval($request->bank_number);
            $data['fee_num'] = intval($request->fee_num);
            $data['jj_mark'] = strval($request->jj_mark);
//            $data['ts_mid'] = intval($request->ts_mid);
//            $data['cp_mid'] = intval($request->cp_mid);
            $data['fee_type_name'] = $request->fee_type_name;
            $data['fee_type_id'] = array_flip(FeeTypeController::$feeTypeCategory)[$request->fee_type_name];

            $data['fee_name'] = $request->fee_name;
            $data['price'] = intval($request->price * 100);             //费用单价
            $data['total_price'] = intval($request->total_price * 100);       //费用金额
            $data['settlement_price'] = intval($request->settlement_price * 100); //结算金额  销售费用的列表
            $data['order_number'] = $request->order_number;
            $data['payment_info'] = is_array($request->payment_info) ? json_encode($request->payment_info) : $request->payment_info;
            $data['pay_bank'] = intval($request->pay_bank);
            $data['remark'] = $otherfeeinfo['remark'];
            $data['other_pid'] = $otherfeeinfo['id'];
            //$data['status'] = 1;
            $otherfee_pay_id = SaleorderOtherfeePay::create($data + ['cpid'=>$cpid])->id;
            SaleorderOtherfeePayApprove::create([
                    'cpid' => $cpid,
                    'otherfee_pay_id'=> $otherfee_pay_id,
                    'otherfee_id'=> $otherfee_id,
                    'ts_mid' => intval($request->ts_mid),
                    'cp_mid' => intval($request->cp_mid),
                    'ts_mid_name' => Manger::where('id',$request->ts_mid)->value('realname'),
                    'cp_mid_name' => Manger::where('id',$request->cp_mid)->value('realname'),
                    'manger_id' => $this->mangerinfo['id'],
                    'manger_name' => Manger::where('id',$this->mangerinfo['id'])->value('realname'),
                    'status' => '1'
                ]);

            //同步更新其他費用选择的往来单位信息
            DB::table('sale_order_otherfee')->where(['id' => $otherfeeinfo['id']])->update([
                'custom_name'=>strval($request->custom_name),
                'company_id'=>intval($request->company_id),
            ]);

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '付款失败，' . $e->getMessage()]);
        }
        //}
        return response()->json(['code' => '000', 'msg' => '付款成功']);
    }

    /****
     *  其他费用往来单位新增
     *
     *
     */
    public function dopostadd2(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'] ?? 0;

        if(empty($request->company_id))
        {
            return response()->json(['code' => '001', 'msg' => '请选择往来单位']);
        }
        //发起付款审核 新增/编辑
        //if($otherfeeinfo->status == '1'){
        DB::beginTransaction();
        try {
            $data = ['is_pay' => 2, 'pay_at' => time(), 'pay_mid' => $this->mangerinfo['id']];
            $data['custom_name'] = strval($request->custom_name ?? '');
            $data['company_id'] = intval($request->company_id);
            $company_name = $request->company_name ?? '';
            $data['company_name'] =$company_name;
            $parts = explode('*', $company_name);
            $data['settlement_company'] = isset($parts[1]) ? $parts[1] : '';
            $data['account_name'] = strval($request->account_name);
            $data['bank_card_no'] = strval($request->bank_card_no);
            $data['bank'] = strval($request->bank);
            $data['bank_number'] = strval($request->bank_number);
            $data['fee_num'] = intval($request->fee_num);
            $data['jj_mark'] = strval($request->jj_mark);
            $data['fee_type_name'] = $request->fee_type_name;
            $data['fee_type_id'] = array_flip(FeeTypeController::$feeTypeCategory)[$request->fee_type_name];

            $data['fee_name'] = $request->fee_name;
            $data['price'] = 0;             //费用单价
            $data['total_price'] = intval($request->total_price * 100);       //费用金额
            $data['settlement_price'] = intval($request->settlement_price * 100); //结算金额  销售费用的列表
            $data['order_number'] = '';
            $data['payment_info'] = is_array($request->payment_info) ? json_encode($request->payment_info) : $request->payment_info;
            $data['pay_bank'] = intval($request->pay_bank);
            //$data['status'] = 1;
            $otherfee_pay_id = SaleorderOtherfeePay::create($data + ['cpid'=>$cpid])->id;
            SaleorderOtherfeePayApprove::create([
                'cpid' => $cpid,
                'otherfee_pay_id'=> $otherfee_pay_id,
                'otherfee_id'=> 0,
                'ts_mid' => intval($request->ts_mid),
                'cp_mid' => intval($request->cp_mid),
                'ts_mid_name' => Manger::where('id',$request->ts_mid)->value('realname'),
                'cp_mid_name' => Manger::where('id',$request->cp_mid)->value('realname'),
                'manger_id' => $this->mangerinfo['id'],
                'manger_name' => Manger::where('id',$this->mangerinfo['id'])->value('realname'),
                'status' => '1'
            ]);


            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '付款失败，' . $e->getMessage()]);
        }
        //}
        return response()->json(['code' => '000', 'msg' => '付款成功']);
    }
    public function getlist(Request $request)
    {
        $isgetall = $request->input('isgetall');
        $list = SaleorderOtherfeePay::getList($request, $this->mangerinfo, $isgetall);

        return response()->json(['code' => '000', 'data' => $list]);
    }
    public function getListbalance(Request $request)
    {
        $isgetall = $request->input('isgetall');
        $list = SaleorderOtherfeePay::getListbalance($request, $this->mangerinfo, $isgetall);

        return response()->json(['code' => '000', 'data' => $list]);
    }
    public function getListBycn(Request $request)
    {
        if ($this->mangerinfo['utype'] != 8) {
            return response()->json(['code' => '001', 'msg' => '您无权限操作']);
        }
        $isgetall = $request->input('isgetall');
        $list = SaleorderOtherfeePay::getListBycn($request, $this->mangerinfo, $isgetall);

        return response()->json(['code' => '000', 'data' => $list]);
    }
    public function getListByTs(Request $request)
    {
        if ($this->mangerinfo['utype'] != 4) {
            return response()->json(['code' => '001', 'msg' => '您无权限操作']);
        }

        $isgetall = $request->input('isgetall');
        $list = SaleorderOtherfeePay::getListByTs($request, $this->mangerinfo, $isgetall);

        return response()->json(['code' => '000', 'data' => $list]);
    }


    public function getListByCp(Request $request)
    {

        if ($this->mangerinfo['utype'] != 2) {
            return response()->json(['code' => '001', 'msg' => '您无权限操作']);
        }

        $isgetall = $request->input('isgetall');
        $list = SaleorderOtherfeePay::getListByCp($request, $this->mangerinfo, $isgetall);

        return response()->json(['code' => '000', 'data' => $list]);
    }
    /****
     *   办款列表
     *
     *
     */
    public function getsublist(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'];
        $pay_id = intval($request->id);

        $SaleorderOtherfeePay = SaleorderOtherfeePay::where(['cpid' => $cpid, 'id' => $pay_id])->first();
        $SaleorderOtherfeeApprove = SaleorderOtherfeePayApprove::where(['cpid' => $cpid, 'otherfee_pay_id' => $pay_id])->first();

        if (!$SaleorderOtherfeePay) {
            return response()->json(['code' => '001', 'msg' => '费用信息不存在']);
        }
        if ($SaleorderOtherfeePay->is_pay != 2) {
            return response()->json(['code' => '001', 'msg' => '费用未支付']);
        }

        if ($SaleorderOtherfeeApprove->status != 3) {
            return response()->json(['code' => '001', 'msg' => '审批完成方可查看']);
        }

        $list = DB::table('sale_order_otherfee_sub')->where(['pid' => $pay_id])->get();

        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    public function getoinfo(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'];

        $pay_id = intval($request->id);
        $SaleorderOtherfeePay = SaleorderOtherfeePay::where('id',$pay_id)->first();
        $Saleorderfee = ModelSaleorderfee::where(['cpid' => $cpid, 'id' => $SaleorderOtherfeePay['other_pid']])->first();
        if (!$Saleorderfee) {
            return response()->json(['code' => '001', 'msg' => '费用信息不存在']);
        }

        $one = ModelSaleorder::with('suborder')->where(['cpid' => $cpid, 'order_number' => $Saleorderfee->order_number])->first();
        $one = $one->toArray();
        if ($one['suborder']) foreach ($one['suborder'] as $key => $value) {
            $one['suborder'][$key]['weight'] = !empty($value['weight']) ? $value['weight'] / 10000 : 0;
            $one['suborder'][$key]['total_weight'] = !empty($value['total_weight']) ? $value['total_weight'] / 10000 : 0;
            $one['suborder'][$key]['unit_price'] = !empty($value['unit_price']) ? $value['unit_price'] / 100 : 0;
            $one['suborder'][$key]['total'] = !empty($value['total']) ? $value['total'] / 100 : 0;
            $one['suborder'][$key]['guiding_price'] = !empty($value['guiding_price']) ? $value['guiding_price'] / 100 : 0;
            $one['suborder'][$key]['accrual'] = !empty($value['accrual']) ? $value['accrual'] / 100 : 0;
            $one['suborder'][$key]['performance'] = !empty($value['performance']) ? $value['performance'] / 100 : 0;
        }
        $one['feeinfo'] = $Saleorderfee;
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
    }
}
